// pages/my/affordorder/affordorder.js
import request from "../../../utils/request";

Page({
  data: {
    isSelected: false,
    orderNo: '',
    orderAmount: 0, // 订单金额
    createTime: '', // 订单创建时间
    countdownText: '15:00', // 倒计时显示文本
    countdownEnded: false, // 倒计时是否结束
    countdownInterval: null, // 倒计时定时器
    orderDetail: {} // 订单详情
  },

  toggleSelect() {
    if (!this.data.countdownEnded) {
      this.setData({
        isSelected: !this.data.isSelected
      })
    }
  },

  handlePay() {
    if (this.data.isSelected && !this.data.countdownEnded) {
      // 调用支付接口
      this.payOrder();
    }
  },

  toMy() {
    wx.navigateBack()
  },

  /**
   * 根据订单编号查询订单详情
   */
  fetchOrderDetail() {
    request({
      url: `/orderManagement/orderManagement/getOrderByOrderNO?orderNo=`+this.data.orderNo, // 根据你的实际接口调整
      method: 'GET'
    }).then(resp => {
      console.log('订单详情：', resp);
      if (resp.data.code == 200) {
        const orderDetail = resp.data.data;
        this.setData({
          orderDetail: orderDetail,
          orderAmount: orderDetail.orderAmount || 0,
          createTime: orderDetail.createTime
        });
        
        // 开始倒计时
        this.startCountdown();
      } else {
        wx.showToast({
          title: '获取订单信息失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('查询订单失败：', err);
      wx.showToast({
        title: '查询订单失败',
        icon: 'none'
      });
    });
  },

  /**
   * 开始倒计时
   */
  startCountdown() {
    if (!this.data.createTime) return;
    
    // 解析创建时间（假设格式为 "YYYY-MM-DD HH:mm:ss"）
    const createTime = new Date(this.data.createTime.replace(/-/g, '/'));
    const endTime = new Date(createTime.getTime() + 15 * 60 * 1000); // 创建时间 + 15分钟
    const now = new Date();
    
    // 计算剩余时间（毫秒）
    let remainingTime = endTime - now;
    
    if (remainingTime <= 0) {
      // 倒计时已结束
      this.setData({
        countdownText: '00:00',
        countdownEnded: true
      });
      return;
    }
    
    // 清除之前的定时器
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
    }
    
    // 更新倒计时显示
    this.updateCountdownText(remainingTime);
    
    // 设置定时器，每秒更新一次
    const countdownInterval = setInterval(() => {
      remainingTime -= 1000;
      
      if (remainingTime <= 0) {
        clearInterval(countdownInterval);
        this.setData({
          countdownText: '00:00',
          countdownEnded: true,
          countdownInterval: null
        });
        return;
      }
      
      this.updateCountdownText(remainingTime);
    }, 1000);
    
    this.setData({
      countdownInterval: countdownInterval
    });
  },

  /**
   * 更新倒计时文本显示
   */
  updateCountdownText(remainingTime) {
    const minutes = Math.floor(remainingTime / (1000 * 60));
    const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);
    
    const minutesText = String(minutes).padStart(2, '0');
    const secondsText = String(seconds).padStart(2, '0');
    
    this.setData({
      countdownText: `${minutesText}:${secondsText}`
    });
  },

  /**
   * 支付订单
   */
  payOrder() {
    wx.showLoading({
      title: '支付中...',
    });
    
    request({
      url: '/orderManagement/orderManagement/updateByOrderNo', // 根据你的实际接口调整
      method: 'PUT',
      data: {
        orderNo: this.data.orderNo,
        orderStatus:1,
        transactionStatus:1
      }
    }).then(resp => {
      wx.hideLoading();
      console.log('支付结果：', resp);
      
      if (resp.data.code == 200) {
        // 支付成功，传递订单号和预期服务时间到成功页面
        const expectedServiceTime = this.data.orderDetail.expectedServiceTime || '';
        wx.navigateTo({
          url: `/pages/my/ordersuccess/ordersuccess?orderNo=${this.data.orderNo}&expectedServiceTime=${encodeURIComponent(expectedServiceTime)}`,
        });
      } else {
        wx.showToast({
          title: resp.data.msg || '支付失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      wx.hideLoading();
      console.error('支付失败：', err);
      wx.showToast({
        title: '支付失败，请重试',
        icon: 'none'
      });
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const orderNo = options.orderNo || options.id || '';
    this.setData({
      orderNo: orderNo
    });
    console.log('接收到的订单编号：', orderNo);
    
    // 查询订单详情
    if (orderNo) {
      this.fetchOrderDetail();
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 清除定时器
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({
        countdownInterval: null
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    // 页面隐藏时清除定时器
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({
        countdownInterval: null
      });
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时重新开始倒计时（如果需要）
    if (this.data.orderNo && !this.data.countdownInterval && !this.data.countdownEnded) {
      this.fetchOrderDetail();
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
});